package com.dreammakerteam.frameworkdemo.qzhj.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.dreammakerteam.frameworkdemo.base.controller.DBaseController;
import com.dreammakerteam.frameworkdemo.base.domain.*;
import com.dreammakerteam.frameworkdemo.base.service.DAreaService;
import com.dreammakerteam.frameworkdemo.base.utils.FileUtil;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQSearchVo;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQzhjProductDo;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQzhjProductHistoryDo;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQProductService;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQzhjProductHistoryService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 清真货架产品
 * @author xy
 * @version 0.1
 */
@RestController
@RequestMapping("/qzhj/prod")
public class DQProductController extends DBaseController {
    @Resource
    private DQProductService dqProductService;

    @Resource
    private SolrClient qzhjSolrClient;

    @Resource
    private DAreaService dAreaService;
    @Resource
    private DQzhjProductHistoryService dQzhjProductHistoryService;

    /**
     * 搜索
     * @param keyword 关键词
     * @return 搜索结果
     */
    @RequestMapping("/search")
    public Object search(String keyword, @RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "10") Integer length) throws IOException, SolrServerException {

        StringBuilder s = new StringBuilder();
        keyword = keyword.replace("<", "&lt;").replace(">", "&gt;");

        System.out.println(keyword);



        HashMap<String, Object> result = new HashMap<>();
        result.put("page", start);

        if (StringUtils.isEmpty(keyword)) {
            Page<DQzhjProductDo> list = dqProductService.list(start, length);


            LinkedList<Map<String, Object>> maps = new LinkedList<>();
            list.getRecords().forEach(dQzhjProductDo -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", dQzhjProductDo.getId().toString());
                map.put("title", dQzhjProductDo.getProdName());
                map.put("content", dQzhjProductDo.getDetailed());

                // 获取地区
                StringBuilder area = new StringBuilder();
                Long provinceId = dQzhjProductDo.getProvinceId();
                if (provinceId != null) {
                    DAreaDo dAreaDo = dAreaService.getMapper().selectById(provinceId);
                    area.append(dAreaDo.getDaName());
                }
                Long cityId = dQzhjProductDo.getCityId();
                if (cityId != null) {
                    DAreaDo dAreaDo = dAreaService.getMapper().selectById(cityId);
                    area.append(' ').append(dAreaDo.getDaName());
                }
                Long areaId = dQzhjProductDo.getAreaId();
                if (areaId != null) {
                    DAreaDo dAreaDo = dAreaService.getMapper().selectById(areaId);
                    area.append(' ').append(dAreaDo.getDaName());
                }
                map.put("area", area.toString());
                map.put("time", dQzhjProductDo.getCreateTime().getTime());
                maps.add(map);
            });
            result.put("total", list.getTotal());
            result.put("data", maps);
        } else {
            SolrQuery query = new SolrQuery().setQuery("title:" + keyword).setStart(start - 1).setRows(length);

            QueryResponse queryResponse = qzhjSolrClient.query(query);
            List<DQSearchVo> results = queryResponse.getBeans(DQSearchVo.class);
            result.put("total", queryResponse.getResults().getNumFound());
            result.put("data", results);
        }
        return result;
    }

    /**
     * 增加产品
     * @param prod 产品信息
     * @return 返回信息
     */
    //@PostMapping("/add")
    public Object add(DQzhjProductDo prod, @RequestParam("images") MultipartFile[] multipartFile) throws IOException, SolrServerException {
        dqProductService.add(prod, FileUtil.uploadFiles(multipartFile));
        return RestResult.successResult;
    }

    /**
     * 更新产品
     * @param prod 产品信息
     * @return 返回信息
     */
    @RequestMapping("/update")
    public Object update(DQzhjProductDo prod) {
        return null;
    }

    /**
     * 获取产品信息
     * @param id 产品id
     * @return 产品信息
     */
    @RequestMapping("/get")
    public Object get(Long id) {


        return null;
    }
    @RequestMapping("/addHistory")
    public Object addHistory(DQzhjProductHistoryDo dQzhjProductHistoryDo) {

        Subject subject = SecurityUtils.getSubject();

        if (!subject.isAuthenticated())
            return new RestResult().setSuccess(false).setMsg("该功能只有管理员才能使用哟！");


        if (StringUtils.isEmpty(dQzhjProductHistoryDo.getContent()))
            throw new DBaseException("追踪信息内容不能为空");

        if (StringUtils.isEmpty(dQzhjProductHistoryDo.getProdId()))
            throw new DBaseException("产品id不能为空");
        dQzhjProductHistoryService.add(dQzhjProductHistoryDo);
        return new RestResult().setResult(dQzhjProductHistoryDo);
    }


    /**
     * 获取产品列表
     * @return 列表
     */
    @RequestMapping("/list")
    public Object list(Integer draw, @RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "10") Integer length) {
        Page<DQzhjProductDo> list = dqProductService.list(start / length + 1, length);
        if (draw != null)
            return DataTablsResult.valueOf(list, draw);
        else {
            HashMap<String, Object> result = new HashMap<>();
            result.put("page", start);
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
            return result;
        }

    }

}
